package com.rfsp.mcp.controller.hos;

import com.rfsp.common.base.ResultListVO;
import com.rfsp.common.shiro.ShiroUtils;
import com.rfsp.common.util.BeanUtil;
import com.rfsp.mcp.controller.base.BaseController;
import com.rfsp.common.pojo.po.OrgPO;
import com.rfsp.mcp.pojo.po.OrgYbjPO;
import com.rfsp.mcp.pojo.po.PfmPO;
import com.rfsp.mcp.pojo.vo.PfmVO;
import com.rfsp.mcp.service.OrgYbjService;
import com.rfsp.mcp.service.PfmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

@Controller("HosController")
@RequestMapping("/hos")
public class HosController extends BaseController {

    @Resource
    PfmService pfmService;

    @Autowired
    private OrgYbjService orgYbjService;

    @GetMapping("/miList")
    public String miList(ModelMap model) {

        OrgPO org = ShiroUtils.getAttribute("org");
        //OrgYbjPO po = ShiroUtils.getAttribute("org_ybj");

        List<PfmVO> miList = pfmService.queryByOrgId(org.getId());
        if(CollectionUtils.isEmpty(miList)){
            return "hos/pfm_null";
        }

        miList.forEach(vo -> vo.setAreaCodeStr(areaService.getFullAddress(vo.getAreaCode())));
        ResultListVO<PfmVO> result = ResultListVO.success(miList);
        model.put("vo", result);
        return "hos/pfm_list";
    }

    @GetMapping("/miList/enter")
    public ModelAndView miListEnter(@RequestParam("id") Long id, @RequestParam("ybjId") Long ybjId, @RequestParam("ybjAid") String ybjAid) {
        try {
            PfmPO po = pfmService.get(id);
            PfmVO pfmvo = BeanUtil.convert(po, PfmVO::new,
                    (s, t) -> t.setAreaCodeStr(areaService.getFullAddress(s.getAreaCode()))
            );
            OrgYbjPO ybjPO = orgYbjService.getOrgYbjByPfmId(id, ybjId, ybjAid);

            logger.info("BASE1 pfmid={}; id={}; aid={}", id, ybjId, ybjAid);
            logger.info("BASE2 pfmid={}; id={}; aid={}", ybjPO.getPfmId(), ybjPO.getId(), ybjPO.getAid());

            ShiroUtils.setAttribute("mcpName", "医保贷业务系统");
            ShiroUtils.setAttribute("mcp_pfm", pfmvo);
            ShiroUtils.setAttribute("org_ybj",  ybjPO);

        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        return redirectView("/login/dash");
    }

}
